﻿namespace MVVMApp_WFBasedBusinessRules.ValidationRules
{
    using System.Windows.Controls;
    using System.Globalization;
    using System.Text.RegularExpressions;
    using System.Text;
    using System.Windows;

    public class MaxDigitValidationRule : ValidationRule
    {
        public int MaxDigits { get; set; }

        public override ValidationResult
            Validate(object value, CultureInfo cultureInfo)
        {
            ValidationResult validationResult =
                ValidationResult.ValidResult;

            string val = string.Format("{0}", value);

            StringBuilder patternBuilder =
                new StringBuilder("^[1-9]{1}[0-9]{0,");
            patternBuilder.Append(MaxDigits - 1);
            patternBuilder.Append("}$");

            if (!Regex.IsMatch(val, patternBuilder.ToString()))
            {
                validationResult =
                    new ValidationResult(false,
                        string.Format(
                        "Invalid Quantity : {0}", val));

            }

            return validationResult;
        }


        public static DependencyProperty MaxDigitsProperty =
            DependencyProperty.Register("MaxDigits", typeof(int), typeof(MaxDigitValidationRule));
        public int MaxDigits
        {
            get { return GetValue(MaxDigits); }
            set
            {
                SetValue
            }
        }
    }
}